import { defineStore } from 'pinia'
import { 
  getBooks, 
  getBookDetail, 
  getCategories, 
  getBookStats,
  getCategoryTree,
  getSubcategories,
  getCategorySankey,
  getCategoryKeywords,
  getCategoryHealth,
  getPriceDistribution,
  getCategoryTop10,
  getPriceTrend
} from '@/api/book'

export const useBookStore = defineStore('book', {
  state: () => ({
    books: [],
    currentBook: null,
    categories: {
      level1: [],
      level2: [],
      level3: []
    },
    stats: null,
    categoryTree: {},
    priceDistribution: [],
    categoryTop10: {
      categories: [],
      counts: []
    },
    priceTrend: {
      dates: [],
      prices: [],
      book_id: null,
      book_title: ''
    },
    loading: false,
    error: null,
    // 新增分页状态
    pagination: {
      current_page: 1,
      per_page: 10,
      total: 0,
      pages: 0,
      has_next: false,
      has_prev: false
    },
    searchQuery: '' // 新增搜索查询
  }),

  actions: {
    async fetchBooks(params = {}) {
      this.loading = true
      try {
        // 合并分页参数和搜索参数
        const response = await getBooks({
          page: this.pagination.current_page,
          per_page: this.pagination.per_page,
          search: this.searchQuery,
          ...params
        })
        
        this.books = response.data
        // 更新分页信息
        if (response.pagination) {
          this.pagination = {
            ...this.pagination,
            ...response.pagination
          }
        }
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    // 新增：改变页码
    async changePage(page) {
      this.pagination.current_page = page
      await this.fetchBooks()
    },

    // 新增：改变每页数量
    async changePerPage(per_page) {
      this.pagination.per_page = per_page
      this.pagination.current_page = 1 // 重置到第一页
      await this.fetchBooks()
    },

    // 新增：搜索书籍
    async searchBooks(query) {
      this.searchQuery = query
      this.pagination.current_page = 1 // 搜索时回到第一页
      await this.fetchBooks()
    },

    // 保留其他原有方法...
    async fetchBookDetail(id) {
      this.loading = true
      try {
        const response = await getBookDetail(id)
        this.currentBook = response.data
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCategories() {
      this.loading = true
      try {
        const response = await getCategories()
        this.categories = response.data
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCategorySankey() {
      this.loading = true
      try {
        const response = await getCategorySankey()
        return response.data
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCategoryKeywords(params) {
      this.loading = true
      try {
        const response = await getCategoryKeywords(params)
        return response.data
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCategoryHealth(params) {
      this.loading = true
      try {
        const response = await getCategoryHealth(params)
        return response.data
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchPriceDistribution() {
      this.loading = true
      try {
        const response = await getPriceDistribution()
        this.priceDistribution = response.data
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchCategoryTop10() {
      this.loading = true
      try {
        const response = await getCategoryTop10()
        this.categoryTop10 = response.data
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchPriceTrend(params) {
      this.loading = true
      try {
        const response = await getPriceTrend(params)
        this.priceTrend = response.data
        return response
      } catch (error) {
        this.error = error
        throw error
      } finally {
        this.loading = false
      }
    }
  },

  getters: {
    // 新增：是否显示分页
    showPagination: (state) => state.pagination.total > state.pagination.per_page,
    
    // 修改原有getters，基于当前页数据
    totalBooks: (state) => state.pagination.total || state.books.length,
    
    averageRating: (state) => {
      if (!state.books.length) return 0
      const sum = state.books.reduce((acc, book) => acc + (book.rating || 0), 0)
      return sum / state.books.length
    },
    
    averagePrice: (state) => {
      if (!state.books.length) return 0
      const sum = state.books.reduce((acc, book) => acc + (book.price || 0), 0)
      return sum / state.books.length
    }
  }
})

